package com.zzx.graduation.controller;



import com.zzx.graduation.config.JwtConfig;
import com.zzx.graduation.entity.User;
import com.zzx.graduation.response.ResponseMessage;
import com.zzx.graduation.response.StateCode;
import com.zzx.graduation.service.UserCRUD;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import javax.transaction.Transactional;
import java.util.List;


//@Transactional
@RestController
@CrossOrigin
@Transactional
public class UserLoginController {

    //slf4j.Logger
    private  static final Logger log = LoggerFactory.getLogger(UserLoginController.class);


    @Autowired
    UserCRUD userService;//Service
    @Resource
    private JwtConfig jwtConfig ;

    /**
     * 用户名密码登录
     * @param username
     * @param password
     * @param response 用于token认证
     * @return
     */
    @RequestMapping(value = "/loginByUserName",method = RequestMethod.POST)
public ResponseMessage userLoginByName(@RequestParam("username") String username,
                                       @RequestParam("password")String password,
                                       HttpServletResponse response){
              log.info("进入controller层loginbyname:"+username+"----"+password);
             User user = userService.loginByName(username,password);
              if(user==null)
              {
                  return  new ResponseMessage<User>(StateCode.NOT_FOUNT,"登陆失败",user);
              }
              else
              {
                  String userId = user.getId() + "";
                  String token = jwtConfig.createToken(userId) ;
                  if (!StringUtils.isEmpty(token)) {
                      //放入响应头
                      response.setHeader("Authorization",token);
                      response.addHeader("Access-Control-Expose-Headers", "Authorization");
                  }

                  //登录状态发到redis
                  //接收历史消息推送



                  return   new ResponseMessage<User>(StateCode.SUCCESS,"登录成功",user);
              }
}



    @RequestMapping(value = "/findByName",method = RequestMethod.POST)
    public ResponseMessage findByName(@RequestParam("staffName") String staffName,
                                           HttpServletResponse response){
        log.info("进入controller层findbyname:"+staffName+"----");
        List<User> users = userService.findByName(staffName);
        if(users==null)
        {
            return  new ResponseMessage<List<User>>(StateCode.NOT_FOUNT,"登陆失败",users);
        }

            return   new ResponseMessage<List<User>>(StateCode.SUCCESS,"登录成功",users);
        }

}
